package net.maku.jw.util;

import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.util.Cookie;
import net.maku.jw.entity.Course;
import net.maku.jw.entity.Student;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlUtil {

    public static String cookieToString(CookieManager CM) {
        String s="";
        Set<Cookie> cookies = CM.getCookies();
        for(Cookie c:cookies){
            String s1 = c.toString();
            s += c.getName() + ":" + c.getValue()+" ";
        }
        return s;
    }

    public static CookieManager stringToCookieManager(String token){
        //切割cookies bzb_jsxsd:AE3EAE3CFEC74B97F30004AD44173884 SERVERID:121
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiesEnabled(true);
        Set<Cookie> cookies;
        String path = "/";
        for (String s : token.split(" ")) {
            String[] keyvalue = s.split(":");
            if (keyvalue[0].equals("bzb_jsxsd"))    path="/jsxsd";
            Cookie cookie = new Cookie(path,keyvalue[0],keyvalue[1]);
            path = "/";
        }
        return cookieManager;
    }



    /**
     * 首页找到班级、身份、姓名、学号   （并保存到数据库，有数据库再说）
     * @param body body
     * @return 用户名
     */
    public static String getFullName(String body) {
        Document doc = Jsoup.parse(body);
        //System.out.println(doc.body().toString());
        Element element = doc.body().getElementsByClass("userInfo").get(0).selectFirst("div");
        //System.out.println(element.getAllElements().get(0).toString());

        Student student = new Student();
        Elements p = element.getElementsByTag("p");
        String span = Objects.requireNonNull(element.selectFirst("span")).text();
        student.setStudentName(p.get(0).text());
        student.setStudentId(p.get(1).text());
        student.setClassName(p.get(2).text());
        student.setId(span);

        return element.text();
    }

    /**
     * 学生学籍卡信息
     * @param  response 网页内容
     * @return 用户名
     */
    public static Student getStudentInfo(String response) throws ParseException {
        Document document = Jsoup.parse(response);

        Element table = document.getElementById("xjkpTable");
        if(table == null) {
            return null;
        }
        Elements trs = table.select("tr");

        Student studentInfo = new Student();

        // 获取学院、专业、学制、学号
        Element tr1 = trs.get(2);
        studentInfo.setCollege(tr1.getElementsByTag("td").get(1).text().substring(5));
        studentInfo.setMajor(tr1.getElementsByTag("td").get(2).text().substring(3));
        studentInfo.setStudentId(tr1.getElementsByTag("td").get(0).text().substring(3));

        Element tr2 = trs.get(3);
        studentInfo.setClassName(tr2.getElementsByTag("td").get(0).text().substring(3));

        Element tr3 = trs.get(4);
        studentInfo.setStudentName(tr3.getElementsByTag("td").get(1).text().replace(Jsoup.parse("&nbsp;").text().trim(), " ").trim());
        studentInfo.setStudentSex(tr3.getElementsByTag("td").get(3).text().replace(Jsoup.parse("&nbsp;").text(), " ").trim());
        //studentInfo.setStudentNamePy(tr2.getElementsByTag("td").get(5).text().replace(Jsoup.parse("&nbsp;").text(), " ").trim());

        // 获取学生政治面貌
        Element tr4 = trs.get(5);
        //studentInfo.setPoliticalStatus(tr4.getElementsByTag("td").get(3).text().replace(Jsoup.parse("&nbsp;").text(), " ").trim());
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
//        Date birthday = simpleDateFormat.parse(tr3.getElementsByTag("td").get(1).text().replace(Jsoup.parse("&nbsp;").text(), " ").trim());
//        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //studentInfo.setBirthday(simpleDateFormat.format(birthday));
        studentInfo.setNation(tr4.getElementsByTag("td").get(5).text().replace(Jsoup.parse("&nbsp;").text().trim(), " ").trim());


        // 入学年份  学制  // fullname 暂时保存入学年份
        Element tr5 = trs.get(6);
        studentInfo.setFullName(tr5.getElementsByTag("td").get(1).text().substring(3).replace(Jsoup.parse("&nbsp;").text(), " ").trim());
        studentInfo.setLearnYear(Integer.parseInt(tr5.getElementsByTag("td").get(5).text().replace(Jsoup.parse("&nbsp;").text(), " ").trim()));
        //studentInfo.setHometown(tr5.getElementsByTag("td").get(1).text().replace(Jsoup.parse("&nbsp;").text(), " ").trim());

        // 获取学生的电话
        //Element tr7 = trs.get(8);
        //String trim5 = tr7.getElementsByTag("td").get(3).text().replace(Jsoup.parse("&nbsp;").text(), " ").trim();
        //studentInfo.setPhone(tr7.getElementsByTag("td").get(3).text().replace(Jsoup.parse("&nbsp;").text(), " ").trim());
        return studentInfo;
    }


    /**
     * 初始化周数据
     * todo  不要这样输入，我很烦呐。直接点不繁琐！ 分为20个周，每一周都遍历一遍保存到数据库  根据班级划分？ 班级加上个人的选修？！ 周次、星期是固定， 时间、课程、地点、任课老师
     * @param body body
     * @return 用户名
     */
    public static String getTable(String body) {

        //读取.html文件为字符串
        String htmlStr = toHtmlString(new File(body));
        //解析字符串为Document对象
        Document doc = Jsoup.parse(htmlStr);
        //获取 table元素
        Element table = doc.body().getElementById("timetable");
        Elements children = table.children();
        //获取tr元素集合
        Elements tr = children.get(0).getElementsByTag("tr");
        //遍历tr元素，获取td元素，并打印
        for(int i=0; i<tr.size(); i++){
            Element e1 = tr.get(i);
            Elements td = e1.getElementsByTag("td");
            for(int j=0; j<td.size(); j++){
                String value = td.get(j).text();
                System.out.print("  "+value + "" +
                        "\n");
            }
            System.out.println();
        }

        return "";
    }


    public static void main(String[] args) throws ParseException {
//        String body = toHtmlString(new File("D:\\Code\\bishe\\maku-boot-v2.x\\maku-boot-new\\src\\main\\java\\net\\maku\\jw\\util\\xueji.html"));
        //System.out.println(getFullName(body));
        //System.out.println(getTable("C:\\JavaDemo\\htmlunit-WebClient-Demo\\src\\main\\resources\\xuanke.html"));

//        Student studentInfo = getStudentInfo(body);
//        System.out.println(studentInfo.toString());
    }




    /**
     *  读取本地html文件里的html代码
     * @return
     */
    public static String toHtmlString(File file) {
        // 获取HTML文件流
        StringBuffer htmlSb = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file), StandardCharsets.UTF_8)); //"unicode"
            while (br.ready()) {
                htmlSb.append(br.readLine());
            }
            br.close();
            // 删除临时文件
            //file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // HTML文件字符串
        String htmlStr = htmlSb.toString();
        // 返回经过清洁的html文本
        return htmlStr;
    }


    public static String getKHString(String input) {
        //String input = "This is some [text] with [multiple] [brackets].";
        String result = "";
        // 提取中括号内部的内容
        Pattern insidePattern = Pattern.compile("\\[(.*?)\\]");
        Matcher insideMatcher = insidePattern.matcher(input);
        while (insideMatcher.find()) {
            result += insideMatcher.group(1);
            //System.out.println("Inside: " + insideMatcher.group(1));
        }
        return result;
    }
}
